<template>
  <div class="guides-page">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <h2>我发表的攻略</h2>
          <el-button type="primary" @click="createGuide">
            <el-icon><Plus /></el-icon>
            写攻略
          </el-button>
        </div>
      </template>

      <!-- 筛选栏 -->
      <div class="filter-bar mb-4">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索攻略"
          class="search-input"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-select
          v-model="filterCategory"
          placeholder="攻略分类"
          @change="handleFilterChange"
        >
          <el-option label="全部" value="" />
          <el-option label="景点游玩" value="spot" />
          <el-option label="美食探店" value="food" />
          <el-option label="住宿推荐" value="hotel" />
          <el-option label="交通出行" value="transport" />
          <el-option label="购物指南" value="shopping" />
          <el-option label="文化体验" value="culture" />
        </el-select>

        <el-select
          v-model="filterStatus"
          placeholder="攻略状态"
          @change="handleFilterChange"
        >
          <el-option label="全部" value="" />
          <el-option label="已发布" value="published" />
          <el-option label="草稿" value="draft" />
          <el-option label="待审核" value="pending" />
        </el-select>

        <el-select
          v-model="sortBy"
          placeholder="排序方式"
          @change="handleSortChange"
        >
          <el-option label="最新发布" value="latest" />
          <el-option label="最多收藏" value="favorites" />
          <el-option label="最多点赞" value="likes" />
          <el-option label="最多评论" value="comments" />
        </el-select>
      </div>

      <!-- 攻略列表 -->
      <div class="guides-list" v-loading="loading">
        <div v-for="guide in paginatedGuides" :key="guide.id" class="guide-item">
          <div class="guide-cover" v-if="guide.coverImage">
            <el-image
              :src="guide.coverImage"
              fit="cover"
              :preview-src-list="[guide.coverImage]"
            />
          </div>
          <div class="guide-main">
            <div class="guide-title">
              <el-tag
                size="small"
                :type="getTagType(guide.status)"
                class="mr-2"
              >
                {{ getStatusText(guide.status) }}
              </el-tag>
              <el-tag size="small" type="info" class="mr-2">
                {{ getCategoryText(guide.category) }}
              </el-tag>
              <router-link :to="'/guide/' + guide.id" class="title-link">
                {{ guide.title }}
              </router-link>
            </div>
            <div class="guide-content">{{ guide.summary }}</div>
            <div class="guide-meta">
              <div class="meta-left">
                <span class="meta-item">
                  <el-icon><Clock /></el-icon>
                  {{ formatDate(guide.createTime) }}
                </span>
                <span class="meta-item">
                  <el-icon><View /></el-icon>
                  {{ guide.viewCount }} 次浏览
                </span>
                <span class="meta-item">
                  <el-icon><Star /></el-icon>
                  {{ guide.favoriteCount }} 次收藏
                </span>
                <span class="meta-item">
                  <el-icon><ThumbUp /></el-icon>
                  {{ guide.likeCount }} 次点赞
                </span>
                <span class="meta-item">
                  <el-icon><ChatDotRound /></el-icon>
                  {{ guide.commentCount }} 条评论
                </span>
              </div>
              <div class="meta-right">
                <el-button-group>
                  <el-button type="primary" link @click="editGuide(guide)">
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-button>
                  <el-button type="danger" link @click="deleteGuide(guide)">
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </el-button-group>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <el-empty
          v-if="!loading && paginatedGuides.length === 0"
          description="暂无攻略"
        />
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  Search,
  Clock,
  View,
  Star,
  ThumbUp,
  ChatDotRound,
  Edit,
  Delete,
} from "@element-plus/icons-vue";
import service from "@/api/axios";

const router = useRouter();

// 状态变量
const loading = ref(false);
const searchKeyword = ref("");
const filterCategory = ref("");
const filterStatus = ref("");
const sortBy = ref("latest");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 测试数据，API请求失败时使用
const mockGuides = [
  {
    id: 4,
    title: "品味贵港：荷花宴里的诗意美食之旅",
    summary: "贵港市因城里多种植荷花而被称为\"荷城\"，这座城市不仅有美丽的荷花景观，更有以荷花为主题的特色美食——荷花宴。本文将带您探索荷花宴的历史渊源、代表菜品和品尝攻略，领略贵港独特的荷花美食文化。",
    category: "food",
    status: "published",
    coverImage: "https://tse1-mm.cn.bing.net/th/id/OIP-C.f54fUZlhK8nAjQiZnFSqYgHaDm?w=346&h=170&c=7&r=0&o=7&cb=iwp2&pid=1.7&rm=3",
    createTime: "2025-05-03 13:26:36",
    viewCount: 356,
    favoriteCount: 48,
    likeCount: 76,
    commentCount: 7,
  },
  {
    id: 5,
    title: "桂平西山：岭南佛教胜地与自然美景的完美融合",
    summary: "桂平西山风景名胜区位于贵港市桂平市城西1公里处，是国家AAAA级景区和国家级风景名胜区。本文详细介绍这个以\"林秀、石奇、泉甘、茶香、佛灵\"五绝著称的岭南名山，为游客提供全面的游览指南。",
    category: "spot",
    status: "published",
    coverImage: "https://tse2-mm.cn.bing.net/th/id/OIP-C.ieSHZOb5QN1caaU6bzPLZQHaEM?w=280&h=180&c=7&r=0&o=7&cb=iwp2&pid=1.7&rm=3",
    createTime: "2025-05-01 13:26:42",
    viewCount: 289,
    favoriteCount: 42,
    likeCount: 63,
    commentCount: 6,
  },
  {
    id: 6,
    title: "探秘罗秀米粉：柳州螺蛳粉背后的\"秘密武器\"",
    summary: "罗秀米粉是广西贵港桂平市罗秀镇的特产，是广西非物质文化遗产，更是柳州螺蛳粉75%米粉的来源地。本文带您探秘这一\"中国一绝\"的历史渊源、制作工艺和美食文化，解读罗秀米粉成为广西名片背后的故事。",
    category: "food",
    status: "published",
    coverImage: "https://tse2-mm.cn.bing.net/th/id/OIP-C.UCqqxbygQDx2YqOSs_uhLQHaHa?w=186&h=186&c=7&r=0&o=7&cb=iwp2&pid=1.7&rm=3",
    createTime: "2025-04-26 13:26:47",
    viewCount: 246,
    favoriteCount: 39,
    likeCount: 58,
    commentCount: 5,
  },
];

// 攻略列表数据
const guidesList = ref([]);

// 获取攻略列表
const getGuidesList = async () => {
  loading.value = true;
  try {
    // 调用获取攻略列表API
    const response = await service.get("/user/guides", {
      params: {
        keyword: searchKeyword.value,
        category: filterCategory.value,
        status: filterStatus.value,
        sortBy: sortBy.value
      }
    });
    
    console.log("后端返回的攻略数据:", response);
    
    // 处理后端返回的数据
    const guidesData = response && response.data ? response.data : [];
    
    if (guidesData && guidesData.length > 0) {
      // 处理后端返回的数据
      guidesList.value = guidesData.map(guide => ({
        ...guide,
        // 确保字段格式一致
        category: guide.category || "other",
        // 处理图片路径
        coverImage: guide.coverImage || guide.image || "/images/guides/default.jpg",
        // 确保必要字段存在
        viewCount: guide.viewCount || 0,
        favoriteCount: guide.favoriteCount || 0,
        likeCount: guide.likeCount || 0,
        commentCount: guide.commentCount || 0,
        // 格式化日期(如果需要)
        createTime: guide.createTime || guide.publishTime || new Date().toISOString(),
      }));
      
      // 更新总数
      total.value = guidesList.value.length;
      console.log("处理后的攻略数据:", guidesList.value);
    } else {
      console.log("后端返回的数据为空，使用测试数据");
      // 如果后端没有数据或返回空数组，使用测试数据
      guidesList.value = [...mockGuides];
      total.value = mockGuides.length;
    }
  } catch (error) {
    console.error("获取攻略列表失败:", error);
    // 出错时使用测试数据
    guidesList.value = [...mockGuides];
    total.value = mockGuides.length;
  } finally {
    loading.value = false;
  }
};

// 计算当前页数据
const paginatedGuides = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return guidesList.value.slice(start, end);
});

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  getGuidesList();
};

// 处理筛选变化
const handleFilterChange = () => {
  currentPage.value = 1;
  getGuidesList();
};

// 处理排序变化
const handleSortChange = () => {
  currentPage.value = 1;
  getGuidesList();
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  // 由于API不支持分页，我们在前端处理分页
};

// 处理每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  // 由于API不支持分页，我们在前端处理分页
};

// 创建攻略
const createGuide = () => {
  router.push("/guide/create");
};

// 编辑攻略
const editGuide = (guide) => {
  router.push(`/guide/edit/${guide.id}`);
};

// 删除攻略
const deleteGuide = async (guide) => {
  try {
    await ElMessageBox.confirm("确定要删除该攻略吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    
    loading.value = true;
    
    try {
      // 调用删除攻略API
      await service.delete(`/user/guides/${guide.id}`);
      ElMessage.success("删除成功");
      
      // 重新获取列表
      getGuidesList();
    } catch (error) {
      console.error("API删除攻略失败:", error);
      
      // 模拟删除成功（仅在开发阶段使用）
      const index = guidesList.value.findIndex(item => item.id === guide.id);
      if (index !== -1) {
        guidesList.value.splice(index, 1);
        total.value -= 1;
      }
      ElMessage.success("删除成功");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除攻略失败:", error);
    }
  } finally {
    loading.value = false;
  }
};

// 获取状态标签类型
const getTagType = (status) => {
  const typeMap = {
    published: "success",
    draft: "info",
    pending: "warning",
  };
  return typeMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    published: "已发布",
    draft: "草稿",
    pending: "待审核",
  };
  return textMap[status] || "未知";
};

// 获取分类文本
const getCategoryText = (category) => {
  const textMap = {
    spot: "景点游玩",
    food: "美食探店",
    hotel: "住宿推荐",
    transport: "交通出行",
    shopping: "购物指南",
    culture: "文化体验",
  };
  return textMap[category] || "其他";
};

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleString();
};

onMounted(() => {
  getGuidesList();
});
</script>

<style lang="scss" scoped>
.guides-page {
  .page-card {
    @apply bg-white dark:bg-gray-800 rounded-lg shadow-sm;

    :deep(.el-card__header) {
      @apply p-0 border-b border-gray-100 dark:border-gray-700;

      .card-header {
        @apply px-6 py-4 flex items-center justify-between;

        h2 {
          @apply text-lg font-medium text-gray-900 dark:text-white;
        }
      }
    }
  }

  .filter-bar {
    @apply flex items-center gap-4;

    .search-input {
      @apply w-64;
    }
  }

  .guides-list {
    @apply space-y-4;

    .guide-item {
      @apply flex items-start p-4 bg-gray-50 dark:bg-gray-800 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-300;

      .guide-cover {
        @apply w-48 h-32 rounded-lg overflow-hidden mr-4 flex-shrink-0;

        :deep(.el-image) {
          @apply w-full h-full;
        }
      }

      .guide-main {
        @apply flex-1 min-w-0;

        .guide-title {
          @apply flex items-center flex-wrap mb-2;

          .title-link {
            @apply text-gray-900 dark:text-white font-medium hover:text-primary-600 dark:hover:text-primary-400 transition-colors duration-300;
          }
        }

        .guide-content {
          @apply text-sm text-gray-500 dark:text-gray-400 mb-3 line-clamp-2;
        }

        .guide-meta {
          @apply flex items-center justify-between;

          .meta-left {
            @apply flex items-center gap-4;

            .meta-item {
              @apply flex items-center text-sm text-gray-500 dark:text-gray-400;

              .el-icon {
                @apply mr-1;
              }
            }
          }
        }
      }
    }
  }

  .pagination-wrapper {
    @apply flex justify-center mt-6;
  }
}
</style>
